import { useState, useEffect, useContext, useRef, useCallback } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { cn } from '@/lib/utils';
import { useTheme } from '@/hooks/useTheme';
import { toast } from 'sonner';
import { AuthContext } from '@/App';
import api, { ApiResponse, addVersion } from '@/services/api';
import { MilkdownPreview } from '@/components/MilkdownPreview';
import { motion, AnimatePresence } from 'framer-motion';
import { emojiCategories } from '@/lib/emoji-data';
import { generateTable } from '@/lib/editor-utils';
import { DocumentData } from '@/lib/types';
import { createPatch } from "diff";
import sha256 from "js-sha256";

export default function Editor() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const { theme, toggleTheme, isDark } = useTheme();
  const { isAuthenticated } = useContext(AuthContext) as any;
  
  const [content, setContent] = useState('');
  const [title, setTitle] = useState('');
  const [docId, setDocId] = useState('');
  const [teamId, setTeamId] = useState('');
  const [projectId, setProjectId] = useState('');
  const [isSaving, setIsSaving] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [wordCount, setWordCount] = useState(0);
  const [charCount, setCharCount] = useState(0);
  const [isEditMode, setIsEditMode] = useState(false);
  const [showTableModal, setShowTableModal] = useState(false);
  const [showEmojiModal, setShowEmojiModal] = useState(false);
  const [selectedCategory, setSelectedCategory] = useState(0);
  const [isEditingTitle, setIsEditingTitle] = useState(false);
  const [autoSaveTimer, setAutoSaveTimer] = useState<number | null>(null);
  const [lastSavedContent, setLastSavedContent] = useState('');
  const [lastSavedTitle, setLastSavedTitle] = useState('');
  const [tableConfig, setTableConfig] = useState({
    rows: 3,
    cols: 3,
    alignment: 'center' // 'default', 'left', 'center', 'right'
  });

  // 模板相关状态
  const [showTemplateModal, setShowTemplateModal] = useState(false);
  const [showSaveTemplateModal, setShowSaveTemplateModal] = useState(false);
  const [templateTitle, setTemplateTitle] = useState('');
  const [templates, setTemplates] = useState<any[]>([]);
  const [selectedTemplateType, setSelectedTemplateType] = useState<'SELF' | 'SYS'>('SELF');
  const [isLoadingTemplates, setIsLoadingTemplates] = useState(false);

  const editorRef = useRef<HTMLDivElement>(null);
  const previewRef = useRef<HTMLDivElement>(null);
  const [isScrolling, setIsScrolling] = useState(false);

  // 使用 useRef 来存储最新的 content 值，避免闭包问题
  const contentRef = useRef(content);
  const titleRef = useRef(title);

  // 同步 ref 和 state
  useEffect(() => {
    contentRef.current = content;
  }, [content]);

  useEffect(() => {
    titleRef.current = title;
  }, [title]);

  // 同步滚动功能
  const handleEditorScroll = (e: React.UIEvent<HTMLTextAreaElement>) => {
    if (isScrolling || isEditMode) return;
    
    setIsScrolling(true);
    const textarea = e.target as HTMLTextAreaElement;
    const scrollTop = textarea.scrollTop;
    const scrollHeight = textarea.scrollHeight;
    const clientHeight = textarea.clientHeight;
    
    // 计算滚动比例
    const scrollRatio = scrollTop / (scrollHeight - clientHeight);
    
    // 同步预览区滚动
    if (previewRef.current) {
      const previewScrollContainer = previewRef.current.querySelector('.overflow-y-auto') as HTMLElement;
      if (previewScrollContainer) {
        const previewScrollHeight = previewScrollContainer.scrollHeight;
        const previewClientHeight = previewScrollContainer.clientHeight;
        const targetScrollTop = scrollRatio * (previewScrollHeight - previewClientHeight);
        previewScrollContainer.scrollTop = targetScrollTop;
      }
    }
    
    // 延迟重置滚动状态
    setTimeout(() => setIsScrolling(false), 50);
  };

  // 计算字数统计
  useEffect(() => {
    const words = content.trim() ? content.trim().split(/\s+/).length : 0;
    const chars = content.length;
    setWordCount(words);
    setCharCount(chars);
  }, [content]);

  // 从URL获取docId，然后调用接口获取文档信息
  useEffect(() => {
    const loadDocumentData = async () => {
      try {
        const docIdFromUrl = searchParams.get('docId');
        if (!docIdFromUrl) {
          toast.error('缺少文档ID');
          navigate(-1);
          return;
        }

        setDocId(docIdFromUrl);
        
        // 调用接口获取文档信息
        const res: ApiResponse = await api({
          url: '/doc/getDocByDocId',
          method: 'post',
          data: {
            docId: docIdFromUrl
          }
        });

        if (res && res.success && res.data) {
          const docData = res.data;
          setContent(docData.docContent || '');
          setTitle(docData.docTitle || '');
          setTeamId(docData.teamId || '');
          setProjectId(docData.projectId || '');
        } else {
          throw new Error(res?.message || '获取文档信息失败');
        }
      } catch (error: any) {
        console.error('加载文档数据失败:', error);
        toast.error(error.message || '加载文档数据失败');
        navigate(-1);
      } finally {
        setIsLoading(false);
      }
    };

    loadDocumentData();
  }, [searchParams, navigate]);

  // 保存文档 - 使用 useCallback 确保获取最新状态
  const handleSave = useCallback(async () => {
    if (!docId) {
      toast.error('文档ID不存在');
      return;
    }

    try {
      setIsSaving(true);
      // 使用 ref 中的最新值，确保获取到当前编辑的内容
      const currentContent = contentRef.current;
      const currentTitle = titleRef.current;
      
      console.log('保存文档:', {
        docId,
        docTitle: currentTitle,
        docContent: currentContent,
        contentLength: currentContent.length
      });

      const res: ApiResponse = await api({
        url: '/doc/editDoc',
        method: 'post',
        data: {
          docId: docId,
          docTitle: currentTitle,
          docContent: currentContent,
          docIcon: 'fa-solid fa-file-lines'
        },
        timeout: 10000
      });

      if (res && res.success) {
        toast.success('文档已保存');
        setLastSavedContent(currentContent); // 更新最后保存的内容
        setLastSavedTitle(currentTitle);
      } else {
        throw new Error(res?.message || '保存失败');
      }
    } catch (error: any) {
      console.error('保存文档失败:', error);
      toast.error(error.message || '保存文档失败');
    } finally {
      setIsSaving(false);
    }
  }, [docId]);

  // 自动保存函数 - 使用 useCallback
  const handleAutoSave = useCallback(async () => {
    // 使用 ref 中的最新值进行比较
    const currentContent = contentRef.current;
    const currentTitle = titleRef.current;
    
    // 只有当内容或标题有变化时才自动保存
    if ((currentContent !== lastSavedContent || currentTitle !== lastSavedTitle) && (currentContent.trim() !== '' || currentTitle.trim() !== '')) {
      await handleSave();
    }
  }, [lastSavedContent, lastSavedTitle, handleSave]);

  // 设置自动保存定时器
  const setupAutoSaveTimer = useCallback(() => {
    // 清除之前的定时器
    if (autoSaveTimer) {
      clearTimeout(autoSaveTimer);
    }
    
    // 设置新的定时器，5秒后自动保存
    const timer = window.setTimeout(() => {
      handleAutoSave();
      setAutoSaveTimer(null);
    }, 5000);
    
    setAutoSaveTimer(timer);
  }, [autoSaveTimer, handleAutoSave]);

  // 处理内容变化
  const handleContentChange = useCallback((newContent: string) => {
    setContent(newContent);
    setupAutoSaveTimer();
  }, [setupAutoSaveTimer]);

  // 处理点击编辑区外部
  const handleClickOutside = useCallback(() => {
    const currentContent = contentRef.current;
    const currentTitle = titleRef.current;
    
    if ((currentContent !== lastSavedContent || currentTitle !== lastSavedTitle) && (currentContent.trim() !== '' || currentTitle.trim() !== '')) {
      handleAutoSave();
    }
  }, [lastSavedContent, lastSavedTitle, handleAutoSave]);

  // 返回项目详情页
  const handleBack = useCallback(async () => {
    const currentContent = contentRef.current;
    const currentTitle = titleRef.current;
    
    // 有内容变化时，先保存再保存版本
    if (
      docId &&
      (currentContent !== lastSavedContent || currentTitle !== lastSavedTitle) &&
      (currentContent.trim() !== '' || currentTitle.trim() !== '')
    ) {
      await handleSave();
      await addVersion({
        docId,
        docContent: currentContent,
        diffContent: getDiffContent(lastSavedContent, currentContent),
        isCurrent: true,
        contentHash: getContentHash(currentContent)
      });
    }
    if (projectId && teamId) {
      navigate(`/project/${projectId}?teamId=${teamId}`);
    } else {
      navigate(-1);
    }
  }, [docId, lastSavedContent, lastSavedTitle, projectId, teamId, navigate, handleSave]);

  // 插入表格
  const insertTable = () => {
    const textarea = document.querySelector('textarea') as HTMLTextAreaElement;
    if (textarea) {
      const start = textarea.selectionStart;
      const table = generateTable(tableConfig.rows, tableConfig.cols, tableConfig.alignment);
      const newText = content.substring(0, start) + '\n' + table + '\n' + content.substring(start);
      setContent(newText);
      
      // 设置光标位置到表格后
      setTimeout(() => {
        textarea.focus();
        const newPosition = start + table.length + 2; // +2 for the newlines
        textarea.setSelectionRange(newPosition, newPosition);
      }, 0);
    }
    setShowTableModal(false);
  };

  // 快捷键支持
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if ((e.ctrlKey || e.metaKey) && e.key === 's') {
        e.preventDefault();
        handleSave();
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [content]);

  // 清理定时器
  useEffect(() => {
    return () => {
      if (autoSaveTimer) {
        clearTimeout(autoSaveTimer);
      }
    };
  }, [autoSaveTimer]);

  // 初始化最后保存的内容
  useEffect(() => {
    if (content && !lastSavedContent) {
      setLastSavedContent(content);
    }
    if (title && !lastSavedTitle) {
      setLastSavedTitle(title);
    }
  }, [content, title, lastSavedContent, lastSavedTitle]);

  // 获取内容 diff
  const getDiffContent = (oldContent: string, newContent: string) => {
    const diff = createPatch('doc', oldContent, newContent);
    return diff;
  };

  // 获取内容 hash
  const getContentHash = (content: string) => {
    return sha256.sha256(content);
  };

  // 加载模板列表
  const loadTemplates = async (type: 'SELF' | 'SYS') => {
    if (!teamId || !projectId) {
      toast.error('缺少团队ID或项目ID');
      return;
    }

    try {
      setIsLoadingTemplates(true);
      const res: ApiResponse = await api({
        url: '/doc/tmp/listTmp',
        method: 'post',
        data: {
          teamId,
          projectId,
          type
        }
      });

      if (res && res.success) {
        setTemplates(res.data || []);
      } else {
        throw new Error(res?.message || '获取模板列表失败');
      }
    } catch (error: any) {
      console.error('获取模板列表失败:', error);
      toast.error(error.message || '获取模板列表失败');
    } finally {
      setIsLoadingTemplates(false);
    }
  };

  // 保存为模板
  const handleSaveAsTemplate = async () => {
    if (!templateTitle.trim()) {
      toast.error('请输入模板标题');
      return;
    }

    if (!teamId || !projectId) {
      toast.error('缺少团队ID或项目ID');
      return;
    }

    try {
      const res: ApiResponse = await api({
        url: '/doc/tmp/addTmp',
        method: 'post',
        data: {
          tmpTitle: templateTitle.trim(),
          tmpContent: content,
          teamId,
          projectId,
          type: 'SELF'
        }
      });

      if (res && res.success) {
        toast.success('模板保存成功');
        setShowSaveTemplateModal(false);
        setTemplateTitle('');
        // 重新加载模板列表
        loadTemplates(selectedTemplateType);
      } else {
        throw new Error(res?.message || '保存模板失败');
      }
    } catch (error: any) {
      console.error('保存模板失败:', error);
      toast.error(error.message || '保存模板失败');
    }
  };

  // 应用模板
  const handleApplyTemplate = (template: any) => {
    setContent(template.tmpContent || '');
    setShowTemplateModal(false);
    toast.success('模板应用成功');
  };

  // 删除模板
  const handleDeleteTemplate = async (tmpId: string) => {
    try {
      const res: ApiResponse = await api({
        url: '/doc/tmp/deleteTmp',
        method: 'post',
        data: { tmpId }
      });

      if (res && res.success) {
        toast.success('模板删除成功');
        // 重新加载模板列表
        loadTemplates(selectedTemplateType);
      } else {
        throw new Error(res?.message || '删除模板失败');
      }
    } catch (error: any) {
      console.error('删除模板失败:', error);
      toast.error(error.message || '删除模板失败');
    }
  };

  if (isLoading) {
    return (
      <div className={cn(
        "min-h-screen flex items-center justify-center",
        isDark ? "bg-gradient-to-br from-gray-900 via-gray-800 to-gray-900" : "bg-gradient-to-br from-gray-50 via-white to-gray-100"
      )}>
        <motion.div 
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="flex flex-col items-center space-y-4"
        >
          <div className={cn(
            "w-16 h-16 rounded-full flex items-center justify-center pulse-glow",
            isDark ? "bg-blue-600/20" : "bg-orange-500/20"
          )}>
            <i className={cn(
              "fa-solid fa-spinner fa-spin text-2xl",
              isDark ? "text-blue-400" : "text-orange-500"
            )}></i>
          </div>
          <span className="text-lg font-medium">加载文档中...</span>
        </motion.div>
      </div>
    );
  }

  return (
    <div className={cn(
      "h-screen flex flex-col overflow-hidden",
      isDark ? "bg-gradient-to-br from-gray-900 via-gray-800 to-gray-900" : "bg-gradient-to-br from-gray-50 via-white to-gray-100"
    )}>
      {/* 顶部导航栏 - 固定 */}
      <motion.header 
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        className={cn(
          "flex-shrink-0 py-0.5 px-1 border-b backdrop-blur-xl bg-opacity-95 shadow-lg",
          isDark ? "bg-gray-800/95 border-gray-700" : "bg-white/95 border-gray-200"
        )}
      >
        <div className="container mx-auto flex justify-between items-center">
          <div className="flex items-center space-x-6">
            <motion.button 
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              onClick={handleBack}
              className={cn(
                "px-4 py-2 rounded-lg font-medium flex items-center transition-all duration-200",
                isDark 
                  ? "bg-gray-700 hover:bg-gray-600 text-gray-200 hover:text-white" 
                  : "bg-gray-100 hover:bg-gray-200 text-gray-700 hover:text-gray-900"
              )}
            >
              <i className="fa-solid fa-arrow-left mr-2"></i>
              返回
            </motion.button>
            <div className="flex flex-col">
              {isEditingTitle ? (
                <div className="flex items-center space-x-2">
                  <input
                    type="text"
                    value={title}
                    onChange={(e) => {
                      setTitle(e.target.value);
                      setupAutoSaveTimer();
                    }}
                    onBlur={() => {
                      setIsEditingTitle(false);
                      handleClickOutside();
                    }}
                    onKeyDown={(e) => {
                      if (e.key === 'Enter') {
                        setIsEditingTitle(false);
                        handleClickOutside();
                      } else if (e.key === 'Escape') {
                        setIsEditingTitle(false);
                      }
                    }}
                    className={cn(
                      "font-bold text-2xl bg-transparent border-b-2 border-blue-500 outline-none px-1",
                      isDark ? "text-white" : "text-gray-900"
                    )}
                    autoFocus
                  />
                  <button
                    onClick={() => setIsEditingTitle(false)}
                    className={cn(
                      "w-6 h-6 rounded-full flex items-center justify-center transition-colors",
                      isDark ? "hover:bg-gray-700 text-gray-400" : "hover:bg-gray-100 text-gray-600"
                    )}
                  >
                    <i className="fa-solid fa-check text-sm"></i>
                  </button>
                </div>
              ) : (
                <div className="flex items-center space-x-2 group">
                  <h1 
                    className="font-bold text-2xl bg-gradient-to-r from-blue-600 to-orange-500 bg-clip-text text-transparent cursor-pointer hover:opacity-80 transition-opacity"
                    onClick={() => setIsEditingTitle(true)}
                  >
                    {title}
                  </h1>
                  <button
                    onClick={() => setIsEditingTitle(true)}
                    className={cn(
                      "w-6 h-6 rounded-full flex items-center justify-center transition-colors opacity-0 group-hover:opacity-100",
                      isDark ? "hover:bg-gray-700 text-gray-400" : "hover:bg-gray-100 text-gray-600"
                    )}
                  >
                    <i className="fa-solid fa-edit text-sm"></i>
                  </button>
                </div>
              )}
            </div>
          </div>
          
          <div className="flex items-center space-x-4">
            {/* 调试信息 */}
            <div className="text-xs text-red-500">DEBUG: 模板按钮区域</div>
            
            <motion.button
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              onClick={() => {
                console.log('模板按钮被点击');
                setShowTemplateModal(true);
              }}
              className={cn(
                "px-4 py-2 rounded-lg font-medium transition-all duration-200 shadow-lg ripple-button",
                "hover:shadow-xl",
                isDark 
                  ? "bg-gradient-to-r from-green-600 to-green-700 hover:from-green-700 hover:to-green-800 text-white" 
                  : "bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 text-white"
              )}
              style={{ border: '2px solid red' }} // 添加红色边框以便调试
            >
              <i className="fa-solid fa-layer-group mr-2"></i>
              模板
            </motion.button>
            <motion.button
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              onClick={() => setShowSaveTemplateModal(true)}
              className={cn(
                "px-4 py-2 rounded-lg font-medium transition-all duration-200 shadow-lg ripple-button",
                "hover:shadow-xl",
                isDark 
                  ? "bg-gradient-to-r from-purple-600 to-purple-700 hover:from-purple-700 hover:to-purple-800 text-white" 
                  : "bg-gradient-to-r from-purple-500 to-purple-600 hover:from-purple-600 hover:to-purple-700 text-white"
              )}
            >
              <i className="fa-solid fa-bookmark mr-2"></i>
              保存为模板
            </motion.button>
            <motion.button
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              onClick={handleSave}
              disabled={isSaving}
              className={cn(
                "px-4 py-2 rounded-lg font-medium transition-all duration-200 shadow-lg ripple-button",
                isSaving 
                  ? "opacity-50 cursor-not-allowed"
                  : "hover:shadow-xl",
                isDark 
                  ? "bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white" 
                  : "bg-gradient-to-r from-orange-500 to-orange-600 hover:from-orange-600 hover:to-orange-700 text-white"
              )}
            >
              {isSaving ? (
                <>
                  <i className="fa-solid fa-spinner fa-spin mr-2"></i>
                  保存中...
                </>
              ) : (
                <>
                  <i className="fa-solid fa-save mr-2"></i>
                  保存文档
                </>
              )}
            </motion.button>
            <motion.button 
              whileHover={{ scale: 1.1, rotate: 180 }}
              whileTap={{ scale: 0.9 }}
              onClick={toggleTheme}
              className={cn(
                "w-12 h-12 rounded-full flex items-center justify-center transition-all duration-300 shadow-lg",
                isDark 
                  ? "bg-gradient-to-r from-gray-700 to-gray-600 hover:from-gray-600 hover:to-gray-500 text-yellow-400" 
                  : "bg-gradient-to-r from-gray-200 to-gray-300 hover:from-gray-300 hover:to-gray-400 text-gray-700"
              )}
            >
              <i className={isDark ? "fa-solid fa-sun" : "fa-solid fa-moon"}></i>
            </motion.button>
          </div>
        </div>
      </motion.header>

      {/* Markdown工具栏 - 固定 */}
      <div className={cn(
        "flex-shrink-0 p-3 border-b",
        isDark ? "bg-gray-800/60 border-gray-700" : "bg-gray-50/60 border-gray-200"
      )}>
        <div className="container mx-auto flex items-center justify-center space-x-2 flex-wrap gap-2">
          {/* 标题工具 */}
          {[
            { icon: 'H1', syntax: '# ', tooltip: '一级标题 (H1)' },
            { icon: 'H2', syntax: '## ', tooltip: '二级标题 (H2)' },
            { icon: 'H3', syntax: '### ', tooltip: '三级标题 (H3)' },
            { icon: 'H4', syntax: '#### ', tooltip: '四级标题 (H4)' },
            { icon: 'H5', syntax: '##### ', tooltip: '五级标题 (H5)' },
            { icon: 'H6', syntax: '###### ', tooltip: '六级标题 (H6)' }
          ].map((item, index) => (
            <motion.button
              key={`heading-${index}`}
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              onClick={() => {
                const textarea = document.querySelector('textarea') as HTMLTextAreaElement;
                if (textarea) {
                  const start = textarea.selectionStart;
                  const end = textarea.selectionEnd;
                  const selectedText = content.substring(start, end);
                  const newText = content.substring(0, start) + item.syntax + (selectedText || '标题') + content.substring(end);
                  handleContentChange(newText);
                  // 设置光标位置
                  setTimeout(() => {
                    textarea.focus();
                    if (selectedText) {
                      textarea.setSelectionRange(start + item.syntax.length, start + item.syntax.length + selectedText.length);
                    } else {
                      textarea.setSelectionRange(start + item.syntax.length + 2, start + item.syntax.length + 2);
                    }
                  }, 0);
                }
              }}
              className={cn(
                "w-8 h-8 rounded flex items-center justify-center transition-all duration-200 toolbar-button ripple-button",
                isDark 
                  ? "bg-gray-700 hover:bg-gray-600 text-gray-300 hover:text-white" 
                  : "bg-gray-200 hover:bg-gray-300 text-gray-700 hover:text-gray-900"
              )}
              title={item.tooltip}
            >
              <span className="text-xs font-bold">{item.icon}</span>
            </motion.button>
          ))}

          {/* 分隔线 */}
          <div className={cn(
            "w-px h-6",
            isDark ? "bg-gray-600" : "bg-gray-300"
          )}></div>

          {/* 文本格式工具 */}
          {[
            { icon: 'fa-solid fa-bold', syntax: '**', tooltip: '粗体文本' },
            { icon: 'fa-solid fa-italic', syntax: '*', tooltip: '斜体文本' },
            { icon: 'fa-solid fa-strikethrough', syntax: '~~', tooltip: '删除线文本' }
          ].map((item, index) => (
            <motion.button
              key={`format-${index}`}
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              onClick={() => {
                const textarea = document.querySelector('textarea') as HTMLTextAreaElement;
                if (textarea) {
                  const start = textarea.selectionStart;
                  const end = textarea.selectionEnd;
                  const selectedText = content.substring(start, end);
                  const newText = content.substring(0, start) + item.syntax + (selectedText || '文本') + item.syntax + content.substring(end);
                  handleContentChange(newText);
                  // 设置光标位置
                  setTimeout(() => {
                    textarea.focus();
                    if (selectedText) {
                      textarea.setSelectionRange(start + item.syntax.length, start + item.syntax.length + selectedText.length);
                    } else {
                      textarea.setSelectionRange(start + item.syntax.length, start + item.syntax.length + 2);
                    }
                  }, 0);
                }
              }}
              className={cn(
                "w-8 h-8 rounded flex items-center justify-center transition-all duration-200 toolbar-button ripple-button",
                isDark 
                  ? "bg-gray-700 hover:bg-gray-600 text-gray-300 hover:text-white" 
                  : "bg-gray-200 hover:bg-gray-300 text-gray-700 hover:text-gray-900"
              )}
              title={item.tooltip}
            >
              <i className={item.icon}></i>
            </motion.button>
          ))}

          {/* 分隔线 */}
          <div className={cn(
            "w-px h-6",
            isDark ? "bg-gray-600" : "bg-gray-300"
          )}></div>

          {/* 列表工具 */}
          {[
            { icon: 'fa-solid fa-list-ul', syntax: '- ', tooltip: '无序列表' },
            { icon: 'fa-solid fa-list-ol', syntax: '1. ', tooltip: '有序列表' }
          ].map((item, index) => (
            <motion.button
              key={`list-${index}`}
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              onClick={() => {
                const textarea = document.querySelector('textarea') as HTMLTextAreaElement;
                if (textarea) {
                  const start = textarea.selectionStart;
                  const end = textarea.selectionEnd;
                  const selectedText = content.substring(start, end);
                  const newText = content.substring(0, start) + item.syntax + (selectedText || '列表项目') + content.substring(end);
                  handleContentChange(newText);
                  // 设置光标位置
                  setTimeout(() => {
                    textarea.focus();
                    if (selectedText) {
                      textarea.setSelectionRange(start + item.syntax.length, start + item.syntax.length + selectedText.length);
                    } else {
                      textarea.setSelectionRange(start + item.syntax.length + 5, start + item.syntax.length + 5);
                    }
                  }, 0);
                }
              }}
              className={cn(
                "w-8 h-8 rounded flex items-center justify-center transition-all duration-200 toolbar-button ripple-button",
                isDark 
                  ? "bg-gray-700 hover:bg-gray-600 text-gray-300 hover:text-white" 
                  : "bg-gray-200 hover:bg-gray-300 text-gray-700 hover:text-gray-900"
              )}
              title={item.tooltip}
            >
              <i className={item.icon}></i>
            </motion.button>
          ))}

          {/* 分隔线 */}
          <div className={cn(
            "w-px h-6",
            isDark ? "bg-gray-600" : "bg-gray-300"
          )}></div>

          {/* 引用和分界线 */}
          {[
            { icon: 'fa-solid fa-quote-left', syntax: '> ', tooltip: '引用块' },
            { icon: 'fa-solid fa-minus', syntax: '\n---\n', tooltip: '水平分界线' }
          ].map((item, index) => (
            <motion.button
              key={`block-${index}`}
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              onClick={() => {
                const textarea = document.querySelector('textarea') as HTMLTextAreaElement;
                if (textarea) {
                  const start = textarea.selectionStart;
                  const end = textarea.selectionEnd;
                  const selectedText = content.substring(start, end);
                  const newText = content.substring(0, start) + item.syntax + (selectedText || '引用内容') + content.substring(end);
                  handleContentChange(newText);
                  // 设置光标位置
                  setTimeout(() => {
                    textarea.focus();
                    if (selectedText) {
                      textarea.setSelectionRange(start + item.syntax.length, start + item.syntax.length + selectedText.length);
                    } else {
                      textarea.setSelectionRange(start + item.syntax.length + 4, start + item.syntax.length + 4);
                    }
                  }, 0);
                }
              }}
              className={cn(
                "w-8 h-8 rounded flex items-center justify-center transition-all duration-200 toolbar-button ripple-button",
                isDark 
                  ? "bg-gray-700 hover:bg-gray-600 text-gray-300 hover:text-white" 
                  : "bg-gray-200 hover:bg-gray-300 text-gray-700 hover:text-gray-900"
              )}
              title={item.tooltip}
            >
              <i className={item.icon}></i>
            </motion.button>
          ))}

          {/* 分隔线 */}
          <div className={cn(
            "w-px h-6",
            isDark ? "bg-gray-600" : "bg-gray-300"
          )}></div>

          {/* 链接工具 */}
          {[
            { icon: 'fa-solid fa-link', syntax: '[链接文本](URL)', tooltip: '插入链接' },
            { icon: 'fa-solid fa-image', syntax: '![alt文本](图片URL)', tooltip: '插入图片' },
            { icon: 'fa-solid fa-video', syntax: '![视频](视频URL)', tooltip: '插入视频链接' }
          ].map((item, index) => (
            <motion.button
              key={`link-${index}`}
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              onClick={() => {
                const textarea = document.querySelector('textarea') as HTMLTextAreaElement;
                if (textarea) {
                  const start = textarea.selectionStart;
                  const end = textarea.selectionEnd;
                  const selectedText = content.substring(start, end);
                  const newText = content.substring(0, start) + item.syntax + content.substring(end);
                  handleContentChange(newText);
                  // 设置光标位置
                  setTimeout(() => {
                    textarea.focus();
                    if (item.syntax.includes('链接文本')) {
                      textarea.setSelectionRange(start + 1, start + 5);
                    } else if (item.syntax.includes('alt文本')) {
                      textarea.setSelectionRange(start + 2, start + 8);
                    } else {
                      textarea.setSelectionRange(start + 2, start + 4);
                    }
                  }, 0);
                }
              }}
              className={cn(
                "w-8 h-8 rounded flex items-center justify-center transition-all duration-200 toolbar-button ripple-button",
                isDark 
                  ? "bg-gray-700 hover:bg-gray-600 text-gray-300 hover:text-white" 
                  : "bg-gray-200 hover:bg-gray-300 text-gray-700 hover:text-gray-900"
              )}
              title={item.tooltip}
            >
              <i className={item.icon}></i>
            </motion.button>
          ))}
          
          {/* 表格按钮 - 单独处理 */}
          <motion.button
            whileHover={{ scale: 1.05 }}
            whileTap={{ scale: 0.95 }}
            onClick={() => setShowTableModal(true)}
            className={cn(
              "w-8 h-8 rounded flex items-center justify-center transition-all duration-200 toolbar-button ripple-button",
              isDark 
                ? "bg-gray-700 hover:bg-gray-600 text-gray-300 hover:text-white" 
                : "bg-gray-200 hover:bg-gray-300 text-gray-700 hover:text-gray-900"
            )}
            title="插入表格"
          >
            <i className="fa-solid fa-table"></i>
          </motion.button>

          {/* 分隔线 */}
          <div className={cn(
            "w-px h-6",
            isDark ? "bg-gray-600" : "bg-gray-300"
          )}></div>

          {/* 表情包按钮 */}
          <motion.button
            whileHover={{ scale: 1.05 }}
            whileTap={{ scale: 0.95 }}
            onClick={() => setShowEmojiModal(true)}
            className={cn(
              "w-8 h-8 rounded flex items-center justify-center transition-all duration-200 toolbar-button ripple-button",
              isDark 
                ? "bg-gray-700 hover:bg-gray-600 text-gray-300 hover:text-white" 
                : "bg-gray-200 hover:bg-gray-300 text-gray-700 hover:text-gray-900"
            )}
            title="插入表情包"
          >
            <span className="text-lg">😊</span>
          </motion.button>

          {/* 分隔线 */}
          <div className={cn(
            "w-px h-6",
            isDark ? "bg-gray-600" : "bg-gray-300"
          )}></div>

          {/* 代码块工具 */}
          {[
            { icon: 'fa-solid fa-code', syntax: '\n```\n', tooltip: '插入代码块' }
          ].map((item, index) => (
            <motion.button
              key={`code-${index}`}
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              onClick={() => {
                const textarea = document.querySelector('textarea') as HTMLTextAreaElement;
                if (textarea) {
                  const start = textarea.selectionStart;
                  const end = textarea.selectionEnd;
                  const selectedText = content.substring(start, end);
                  const newText = content.substring(0, start) + '\n```\n' + (selectedText || '代码内容') + '\n```\n' + content.substring(end);
                  handleContentChange(newText);
                  // 设置光标位置
                  setTimeout(() => {
                    textarea.focus();
                    if (selectedText) {
                      textarea.setSelectionRange(start + 5, start + 5 + selectedText.length);
                    } else {
                      textarea.setSelectionRange(start + 5, start + 5 + 4);
                    }
                  }, 0);
                }
              }}
              className={cn(
                "w-8 h-8 rounded flex items-center justify-center transition-all duration-200 toolbar-button ripple-button",
                isDark 
                  ? "bg-gray-700 hover:bg-gray-600 text-gray-300 hover:text-white" 
                  : "bg-gray-200 hover:bg-gray-300 text-gray-700 hover:text-gray-900"
              )}
              title={item.tooltip}
            >
              <i className={item.icon}></i>
            </motion.button>
          ))}

          {/* 分隔线 */}
          <div className={cn(
            "w-px h-6",
            isDark ? "bg-gray-600" : "bg-gray-300"
          )}></div>

          {/* 实用工具 */}
          {[
            { icon: 'fa-solid fa-calendar', syntax: '', tooltip: '插入当前日期时间' },
            { icon: 'fa-solid fa-file-lines', syntax: '\n<div style="page-break-after: always;"></div>\n', tooltip: '插入分页符' }
          ].map((item, index) => (
            <motion.button
              key={`util-${index}`}
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              onClick={() => {
                const textarea = document.querySelector('textarea') as HTMLTextAreaElement;
                if (textarea) {
                  const start = textarea.selectionStart;
                  const end = textarea.selectionEnd;
                  let newText;
                  let insertedLength = 0;
                  
                  if (item.syntax === '') {
                    const now = new Date();
                    const year = now.getFullYear();
                    const month = String(now.getMonth() + 1).padStart(2, '0');
                    const day = String(now.getDate()).padStart(2, '0');
                    const hours = String(now.getHours()).padStart(2, '0');
                    const minutes = String(now.getMinutes()).padStart(2, '0');
                    const seconds = String(now.getSeconds()).padStart(2, '0');
                    const dateStr = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                    newText = content.substring(0, start) + dateStr + content.substring(end);
                    insertedLength = dateStr.length;
                  } else {
                    newText = content.substring(0, start) + item.syntax + content.substring(end);
                    insertedLength = item.syntax.length;
                  }
                  
                  handleContentChange(newText);
                  
                  // 立即设置光标位置并聚焦
                  textarea.focus();
                  textarea.setSelectionRange(start + insertedLength, start + insertedLength);
                  
                  // 确保编辑区可见
                  textarea.scrollIntoView({ behavior: 'smooth', block: 'center' });
                }
              }}
              className={cn(
                "w-8 h-8 rounded flex items-center justify-center transition-all duration-200 toolbar-button ripple-button",
                isDark 
                  ? "bg-gray-700 hover:bg-gray-600 text-gray-300 hover:text-white" 
                  : "bg-gray-200 hover:bg-gray-300 text-gray-700 hover:text-gray-900"
              )}
              title={item.tooltip}
            >
              <i className={item.icon}></i>
            </motion.button>
          ))}
        </div>
      </div>

      {/* 主内容区域 - 可滚动 */}
      <main className="flex-1 flex min-h-0 overflow-hidden">
        <div className={cn(
          "w-full h-full",
          isEditMode ? "flex justify-center" : "max-w-7xl mx-auto flex gap-6"
        )}>
          {/* 左侧编辑器 */}
          <motion.div 
            initial={{ opacity: 0, x: -50 }}
            animate={{ opacity: 1, x: 0 }}
            className="flex flex-col relative h-full"
            style={{ 
              width: isEditMode ? '800px' : '50%', 
              minWidth: isEditMode ? '600px' : '300px',
              maxWidth: isEditMode ? '800px' : 'none'
            }}
            ref={editorRef}
          >
            <div className={cn(
              "flex-shrink-0 p-2 border-b rounded-t-xl",
              isDark ? "bg-gray-800/80 border-gray-700" : "bg-white/80 border-gray-200"
            )}>
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-4 text-xs text-gray-500">
                  <span>字数: {wordCount}</span>
                  <span>字符: {charCount}</span>
                </div>
                {/* 编辑模式下的预览按钮 */}
                {isEditMode && (
                  <motion.button
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                    onClick={() => setIsEditMode(false)}
                    className="text-sm font-medium text-gray-600 dark:text-gray-400 flex items-center hover:text-blue-500 dark:hover:text-blue-400 transition-colors"
                    title="切换回预览模式"
                  >
                    <i className="fa-solid fa-eye mr-2"></i>
                    预览
                  </motion.button>
                )}
              </div>
            </div>
            
            <div className={cn(
              "flex-1 overflow-hidden rounded-b-xl shadow-xl",
              isDark ? "bg-gray-900/80" : "bg-white/80"
            )}>
              <textarea
                value={content}
                onChange={(e) => handleContentChange(e.target.value)}
                onBlur={handleClickOutside}
                className={cn(
                  "w-full h-full p-6 resize-none border-0 outline-none font-mono text-sm leading-relaxed editor-textarea custom-scrollbar",
                  isDark 
                    ? "bg-gray-900/80 text-gray-100 placeholder-gray-500" 
                    : "bg-white/80 text-gray-900 placeholder-gray-400"
                )}
                placeholder="请输入Markdown内容...

# 标题1
## 标题2

**粗体文本** 和 *斜体文本*

- 列表项目1
- 列表项目2

| 表格 | 示例 |
|------|------|
| 内容1 | 内容2 |

```javascript
// 代码块示例
function hello() {
  return 'Hello World!';
}
```"
                onScroll={handleEditorScroll}
              />
            </div>
          </motion.div>

          {/* 可拖动的分界线 - 只在非编辑模式时显示 */}
          {!isEditMode && (
            <div 
              className={cn(
                "w-1 cursor-col-resize flex-shrink-0 rounded bg-gray-300 dark:bg-gray-700 transition-colors duration-200",
                "hover:bg-blue-400 dark:hover:bg-blue-500"
              )}
              style={{ minHeight: '480px', margin: '0 0' }}
              onMouseDown={(e) => {
                e.preventDefault();
                const startX = e.clientX;
                const startEditorWidth = editorRef.current?.clientWidth || 400;
                const startPreviewWidth = previewRef.current?.clientWidth || 400;
                
                const handleMouseMove = (moveEvent: MouseEvent) => {
                  const dx = moveEvent.clientX - startX;
                  const newEditorWidth = Math.max(300, Math.min(800, startEditorWidth + dx));
                  const newPreviewWidth = Math.max(300, startPreviewWidth - dx);
                  
                  if (editorRef.current) {
                    editorRef.current.style.width = `${newEditorWidth}px`;
                  }
                  if (previewRef.current) {
                    previewRef.current.style.width = `${newPreviewWidth}px`;
                  }
                };

                const handleMouseUp = () => {
                  document.removeEventListener('mousemove', handleMouseMove);
                  document.removeEventListener('mouseup', handleMouseUp);
                };

                document.addEventListener('mousemove', handleMouseMove);
                document.addEventListener('mouseup', handleMouseUp);
              }}
            />
          )}

          {/* 右侧预览 - 只在非编辑模式时显示 */}
          {!isEditMode && (
            <motion.div 
              initial={{ opacity: 0, x: 50 }}
              animate={{ opacity: 1, x: 0 }}
              className="flex flex-col h-full"
              style={{ width: '50%', minWidth: '300px' }}
              ref={previewRef}
            >
              <div className={cn(
                "flex-shrink-0 p-2 border-b rounded-t-xl",
                isDark ? "bg-gray-800/80 border-gray-700" : "bg-white/80 border-gray-200"
              )}>
                <motion.button
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.95 }}
                  onClick={() => setIsEditMode(true)}
                  className="text-sm font-medium text-gray-600 dark:text-gray-400 flex items-center hover:text-blue-500 dark:hover:text-blue-400 transition-colors"
                  title="切换到编辑模式"
                >
                  <i className="fa-solid fa-eye mr-2"></i>
                  预览区域
                </motion.button>
              </div>
              <div className={cn(
                "flex-1 overflow-hidden rounded-b-xl shadow-xl preview-container",
                isDark ? "bg-gray-900/80" : "bg-white/80"
              )}>
                <div className={cn(
                  "w-full h-full overflow-y-auto custom-scrollbar",
                  isDark ? "bg-gray-900/80" : "bg-white/80"
                )}>
                  <div className="p-6 max-w-5xl mx-auto">
                    <MilkdownPreview 
                      content={content || "请编辑文档内容"}
                      isDark={isDark}
                      className="text-base"
                    />
                  </div>
                </div>
              </div>
            </motion.div>
          )}
        </div>
      </main>

      {/* 底部工具栏 */}
      <motion.div 
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className={cn(
          "flex-shrink-0 p-2 border-t backdrop-blur-xl bg-opacity-95",
          isDark ? "bg-gray-800/95 border-gray-700" : "bg-white/95 border-gray-200"
        )}
      >
        <div className="container mx-auto flex items-center justify-between text-sm text-gray-500 dark:text-gray-400">
          <div className="flex items-center space-x-6">
            <span className="flex items-center">
              <i className="fa-solid fa-keyboard mr-2 text-blue-500"></i>
              支持所有 Markdown 语法
            </span>
            <span className="flex items-center">
              <i className="fa-solid fa-clock mr-2 text-green-500"></i>
              实时预览
            </span>
            <span className="flex items-center">
              <i className="fa-solid fa-chart-line mr-2 text-purple-500"></i>
              字数统计
            </span>
          </div>
          <div className="flex items-center space-x-3">
            <span className="font-medium">快捷键:</span>
            <kbd className="px-3 py-1 text-xs bg-gray-200 dark:bg-gray-700 rounded-lg shadow-inner font-mono">
              Ctrl+S
            </kbd>
            <span>保存文档</span>
          </div>
        </div>
      </motion.div>

      {/* 表格配置弹框 */}
      <AnimatePresence>
        {showTableModal && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4"
            style={{ top: '50%', left: '50%', transform: 'translate(-50%, -50%)' }}
            onClick={() => setShowTableModal(false)}
          >
            <motion.div
              initial={{ scale: 0.9, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.9, opacity: 0 }}
              className={cn(
                "w-full max-w-sm p-4 rounded-2xl shadow-2xl",
                isDark ? "bg-gray-800 border border-gray-700" : "bg-white border border-gray-200"
              )}
              onClick={(e) => e.stopPropagation()}
            >
              <div className="flex items-center justify-between mb-4">
                <h3 className={cn(
                  "text-xl font-bold",
                  isDark ? "text-white" : "text-gray-900"
                )}>
                  <i className="fa-solid fa-table mr-3 text-blue-500"></i>
                  插入表格
                </h3>
                <button
                  onClick={() => setShowTableModal(false)}
                  className={cn(
                    "w-8 h-8 rounded-full flex items-center justify-center transition-colors",
                    isDark ? "hover:bg-gray-700 text-gray-400" : "hover:bg-gray-100 text-gray-600"
                  )}
                >
                  <i className="fa-solid fa-times"></i>
                </button>
              </div>

              <div className="space-y-4">
                {/* 行数设置 */}
                <div>
                  <label className={cn(
                    "block text-sm font-medium mb-2",
                    isDark ? "text-gray-300" : "text-gray-700"
                  )}>
                    行数
                  </label>
                  <input
                    type="number"
                    min="1"
                    max="20"
                    value={tableConfig.rows}
                    onChange={(e) => setTableConfig(prev => ({ ...prev, rows: parseInt(e.target.value) || 1 }))}
                    className={cn(
                      "w-full px-3 py-2 rounded-lg border transition-colors focus:outline-none focus:ring-2",
                      isDark 
                        ? "bg-gray-700 border-gray-600 text-white focus:ring-blue-500 focus:border-blue-500" 
                        : "bg-white border-gray-300 text-gray-900 focus:ring-blue-500 focus:border-blue-500"
                    )}
                  />
                </div>

                {/* 列数设置 */}
                <div>
                  <label className={cn(
                    "block text-sm font-medium mb-2",
                    isDark ? "text-gray-300" : "text-gray-700"
                  )}>
                    列数
                  </label>
                  <input
                    type="number"
                    min="1"
                    max="10"
                    value={tableConfig.cols}
                    onChange={(e) => setTableConfig(prev => ({ ...prev, cols: parseInt(e.target.value) || 1 }))}
                    className={cn(
                      "w-full px-3 py-2 rounded-lg border transition-colors focus:outline-none focus:ring-2",
                      isDark 
                        ? "bg-gray-700 border-gray-600 text-white focus:ring-blue-500 focus:border-blue-500" 
                        : "bg-white border-gray-300 text-gray-900 focus:ring-blue-500 focus:border-blue-500"
                    )}
                  />
                </div>

                {/* 对齐方式设置 */}
                <div>
                  <label className={cn(
                    "block text-sm font-medium mb-2",
                    isDark ? "text-gray-300" : "text-gray-700"
                  )}>
                    对齐方式
                  </label>
                  <div className="grid grid-cols-2 gap-2">
                    {[
                      { value: 'default', label: '两边对齐', icon: 'fa-solid fa-arrows-left-right' },
                      { value: 'left', label: '左对齐', icon: 'fa-solid fa-align-left' },
                      { value: 'center', label: '居中对齐', icon: 'fa-solid fa-align-center' },
                      { value: 'right', label: '右对齐', icon: 'fa-solid fa-align-right' }
                    ].map((option) => (
                      <button
                        key={option.value}
                        onClick={() => setTableConfig(prev => ({ ...prev, alignment: option.value }))}
                        className={cn(
                          "px-3 py-2 rounded-lg border transition-all duration-200 flex items-center justify-center space-x-2",
                          tableConfig.alignment === option.value
                            ? "border-blue-500 bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400"
                            : isDark
                              ? "border-gray-600 bg-gray-700 text-gray-300 hover:bg-gray-600"
                              : "border-gray-300 bg-white text-gray-700 hover:bg-gray-50"
                        )}
                      >
                        <i className={option.icon}></i>
                        <span className="text-sm">{option.label}</span>
                      </button>
                    ))}
                  </div>
                </div>

                {/* 预览 */}
                <div>
                  <label className={cn(
                    "block text-sm font-medium mb-2",
                    isDark ? "text-gray-300" : "text-gray-700"
                  )}>
                    预览
                  </label>
                  <div className={cn(
                    "p-3 rounded-lg border text-xs font-mono overflow-x-auto",
                    isDark ? "bg-gray-900 border-gray-600 text-gray-300" : "bg-gray-50 border-gray-300 text-gray-700"
                  )}>
                    <pre>{generateTable(tableConfig.rows, tableConfig.cols, tableConfig.alignment)}</pre>
                  </div>
                </div>
              </div>

              {/* 操作按钮 */}
              <div className="flex space-x-3 mt-4">
                <motion.button
                  whileHover={{ scale: 1.02 }}
                  whileTap={{ scale: 0.98 }}
                  onClick={() => setShowTableModal(false)}
                  className={cn(
                    "flex-1 px-4 py-2 rounded-lg font-medium transition-colors",
                    isDark 
                      ? "bg-gray-700 hover:bg-gray-600 text-gray-300" 
                      : "bg-gray-200 hover:bg-gray-300 text-gray-700"
                  )}
                >
                  取消
                </motion.button>
                <motion.button
                  whileHover={{ scale: 1.02 }}
                  whileTap={{ scale: 0.98 }}
                  onClick={insertTable}
                  className="flex-1 px-4 py-2 rounded-lg font-medium bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white transition-all duration-200 shadow-lg"
                >
                  <i className="fa-solid fa-plus mr-2"></i>
                  插入表格
                </motion.button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* 表情包选择器弹框 */}
      <AnimatePresence>
        {showEmojiModal && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center p-4"
            style={{ top: '50%', left: '50%', transform: 'translate(-50%, -50%)' }}
            onClick={() => setShowEmojiModal(false)}
          >
            <motion.div
              initial={{ scale: 0.9, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.9, opacity: 0 }}
              className={cn(
                "w-full max-w-2xl p-6 rounded-2xl shadow-2xl max-h-[80vh] overflow-hidden",
                isDark ? "bg-gray-800 border border-gray-700" : "bg-white border border-gray-200"
              )}
              onClick={(e) => e.stopPropagation()}
            >
              <div className="flex items-center justify-between mb-4">
                <h3 className={cn(
                  "text-xl font-bold",
                  isDark ? "text-white" : "text-gray-900"
                )}>
                  <span className="mr-3">😊</span>
                  选择表情包
                </h3>
                <button
                  onClick={() => setShowEmojiModal(false)}
                  className={cn(
                    "w-8 h-8 rounded-full flex items-center justify-center transition-colors",
                    isDark ? "hover:bg-gray-700 text-gray-400" : "hover:bg-gray-100 text-gray-600"
                  )}
                >
                  <i className="fa-solid fa-times"></i>
                </button>
              </div>

              {/* 分类标签 */}
              <div className="flex flex-wrap gap-2 mb-4 pb-4 border-b">
                {emojiCategories.map((category, index) => (
                  <motion.button
                    key={category.name}
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                    className={cn(
                      "px-3 py-2 rounded-lg text-sm font-medium transition-all duration-200 flex items-center space-x-2",
                      index === 0
                        ? "bg-blue-500 text-white shadow-lg"
                        : isDark
                          ? "bg-gray-700 text-gray-300 hover:bg-gray-600"
                          : "bg-gray-200 text-gray-700 hover:bg-gray-300"
                    )}
                    onClick={() => setSelectedCategory(index)}
                  >
                    <span className="text-lg">{category.icon}</span>
                    <span>{category.name}</span>
                  </motion.button>
                ))}
              </div>

              {/* 表情包网格 */}
              <div className="grid grid-cols-10 gap-2 max-h-96 overflow-y-auto custom-scrollbar">
                {emojiCategories[selectedCategory]?.emojis.map((emoji, index) => (
                  <motion.button
                    key={`${selectedCategory}-${index}`}
                    whileHover={{ scale: 1.2 }}
                    whileTap={{ scale: 0.9 }}
                    className={cn(
                      "w-10 h-10 rounded-lg flex items-center justify-center text-xl transition-all duration-200",
                      isDark 
                        ? "hover:bg-gray-700 hover:shadow-lg" 
                        : "hover:bg-gray-200 hover:shadow-md"
                    )}
                    onClick={() => {
                      const textarea = document.querySelector('textarea') as HTMLTextAreaElement;
                      if (textarea) {
                        const start = textarea.selectionStart;
                        const newText = content.substring(0, start) + emoji + content.substring(start);
                        handleContentChange(newText);
                        
                        // 设置光标位置
                        setTimeout(() => {
                          textarea.focus();
                          textarea.setSelectionRange(start + emoji.length, start + emoji.length);
                        }, 0);
                      }
                      setShowEmojiModal(false);
                    }}
                    title={emoji}
                  >
                    {emoji}
                  </motion.button>
                ))}
              </div>

              {/* 底部提示 */}
              <div className="mt-4 pt-4 border-t text-center">
                <p className={cn(
                  "text-sm",
                  isDark ? "text-gray-400" : "text-gray-600"
                )}>
                  点击表情包即可插入到文档中
                </p>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* 模板选择弹框 */}
      <AnimatePresence>
        {showTemplateModal && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4"
            onClick={() => setShowTemplateModal(false)}
          >
            <motion.div
              initial={{ scale: 0.9, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.9, opacity: 0 }}
              className={cn(
                "w-full max-w-4xl p-6 rounded-2xl shadow-2xl max-h-[80vh] overflow-hidden",
                isDark ? "bg-gray-800 border border-gray-700" : "bg-white border border-gray-200"
              )}
              onClick={(e) => e.stopPropagation()}
            >
              <div className="flex items-center justify-between mb-4">
                <h3 className={cn(
                  "text-xl font-bold",
                  isDark ? "text-white" : "text-gray-900"
                )}>
                  <i className="fa-solid fa-layer-group mr-3 text-green-500"></i>
                  选择模板
                </h3>
                <button
                  onClick={() => setShowTemplateModal(false)}
                  className={cn(
                    "w-8 h-8 rounded-full flex items-center justify-center transition-colors",
                    isDark ? "hover:bg-gray-700 text-gray-400" : "hover:bg-gray-100 text-gray-600"
                  )}
                >
                  <i className="fa-solid fa-times"></i>
                </button>
              </div>

              {/* 模板类型切换 */}
              <div className="flex space-x-2 mb-4">
                {[
                  { type: 'SELF' as const, label: '我的模板', icon: 'fa-solid fa-user' },
                  { type: 'SYS' as const, label: '系统模板', icon: 'fa-solid fa-cog' }
                ].map((item) => (
                  <motion.button
                    key={item.type}
                    whileHover={{ scale: 1.02 }}
                    whileTap={{ scale: 0.98 }}
                    onClick={() => {
                      setSelectedTemplateType(item.type);
                      loadTemplates(item.type);
                    }}
                    className={cn(
                      "px-4 py-2 rounded-lg font-medium transition-all duration-200 flex items-center space-x-2",
                      selectedTemplateType === item.type
                        ? "bg-green-500 text-white shadow-lg"
                        : isDark
                          ? "bg-gray-700 text-gray-300 hover:bg-gray-600"
                          : "bg-gray-200 text-gray-700 hover:bg-gray-300"
                    )}
                  >
                    <i className={item.icon}></i>
                    <span>{item.label}</span>
                  </motion.button>
                ))}
              </div>

              {/* 模板列表 */}
              <div className="max-h-96 overflow-y-auto custom-scrollbar">
                {isLoadingTemplates ? (
                  <div className="flex items-center justify-center h-32">
                    <i className="fa-solid fa-spinner fa-spin text-2xl mr-2"></i>
                    <span>加载模板中...</span>
                  </div>
                ) : templates.length === 0 ? (
                  <div className="text-center py-8">
                    <i className="fa-solid fa-inbox text-4xl text-gray-400 mb-2"></i>
                    <p className="text-gray-500">暂无模板</p>
                  </div>
                ) : (
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {templates.map((template) => (
                      <motion.div
                        key={template.tmpId}
                        whileHover={{ scale: 1.02 }}
                        className={cn(
                          "p-4 rounded-lg border transition-all duration-200 cursor-pointer",
                          isDark 
                            ? "bg-gray-700 border-gray-600 hover:bg-gray-600" 
                            : "bg-gray-50 border-gray-200 hover:bg-gray-100"
                        )}
                      >
                        <div className="flex items-start justify-between">
                          <div className="flex-1">
                            <h4 className={cn(
                              "font-medium mb-2",
                              isDark ? "text-white" : "text-gray-900"
                            )}>
                              {template.tmpTitle}
                            </h4>
                            <p className={cn(
                              "text-sm line-clamp-3",
                              isDark ? "text-gray-400" : "text-gray-600"
                            )}>
                              {template.tmpContent?.substring(0, 100)}...
                            </p>
                          </div>
                          <div className="flex space-x-2 ml-4">
                            <motion.button
                              whileHover={{ scale: 1.1 }}
                              whileTap={{ scale: 0.9 }}
                              onClick={() => handleApplyTemplate(template)}
                              className={cn(
                                "w-8 h-8 rounded-full flex items-center justify-center transition-colors",
                                isDark 
                                  ? "bg-green-600 hover:bg-green-700 text-white" 
                                  : "bg-green-500 hover:bg-green-600 text-white"
                              )}
                              title="应用模板"
                            >
                              <i className="fa-solid fa-check text-sm"></i>
                            </motion.button>
                            {selectedTemplateType === 'SELF' && (
                              <motion.button
                                whileHover={{ scale: 1.1 }}
                                whileTap={{ scale: 0.9 }}
                                onClick={() => handleDeleteTemplate(template.tmpId)}
                                className={cn(
                                  "w-8 h-8 rounded-full flex items-center justify-center transition-colors",
                                  isDark 
                                    ? "bg-red-600 hover:bg-red-700 text-white" 
                                    : "bg-red-500 hover:bg-red-600 text-white"
                                )}
                                title="删除模板"
                              >
                                <i className="fa-solid fa-trash text-sm"></i>
                              </motion.button>
                            )}
                          </div>
                        </div>
                      </motion.div>
                    ))}
                  </div>
                )}
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* 保存为模板弹框 */}
      <AnimatePresence>
        {showSaveTemplateModal && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4"
            onClick={() => setShowSaveTemplateModal(false)}
          >
            <motion.div
              initial={{ scale: 0.9, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.9, opacity: 0 }}
              className={cn(
                "w-full max-w-md p-6 rounded-2xl shadow-2xl",
                isDark ? "bg-gray-800 border border-gray-700" : "bg-white border border-gray-200"
              )}
              onClick={(e) => e.stopPropagation()}
            >
              <div className="flex items-center justify-between mb-4">
                <h3 className={cn(
                  "text-xl font-bold",
                  isDark ? "text-white" : "text-gray-900"
                )}>
                  <i className="fa-solid fa-bookmark mr-3 text-purple-500"></i>
                  保存为模板
                </h3>
                <button
                  onClick={() => setShowSaveTemplateModal(false)}
                  className={cn(
                    "w-8 h-8 rounded-full flex items-center justify-center transition-colors",
                    isDark ? "hover:bg-gray-700 text-gray-400" : "hover:bg-gray-100 text-gray-600"
                  )}
                >
                  <i className="fa-solid fa-times"></i>
                </button>
              </div>

              <div className="space-y-4">
                <div>
                  <label className={cn(
                    "block text-sm font-medium mb-2",
                    isDark ? "text-gray-300" : "text-gray-700"
                  )}>
                    模板标题
                  </label>
                  <input
                    type="text"
                    value={templateTitle}
                    onChange={(e) => setTemplateTitle(e.target.value)}
                    placeholder="请输入模板标题"
                    className={cn(
                      "w-full px-3 py-2 rounded-lg border transition-colors focus:outline-none focus:ring-2",
                      isDark 
                        ? "bg-gray-700 border-gray-600 text-white focus:ring-purple-500 focus:border-purple-500" 
                        : "bg-white border-gray-300 text-gray-900 focus:ring-purple-500 focus:border-purple-500"
                    )}
                    autoFocus
                  />
                </div>

                <div>
                  <label className={cn(
                    "block text-sm font-medium mb-2",
                    isDark ? "text-gray-300" : "text-gray-700"
                  )}>
                    预览内容
                  </label>
                  <div className={cn(
                    "p-3 rounded-lg border text-sm max-h-32 overflow-y-auto",
                    isDark ? "bg-gray-900 border-gray-600 text-gray-300" : "bg-gray-50 border-gray-300 text-gray-700"
                  )}>
                    {content.substring(0, 200)}...
                  </div>
                </div>
              </div>

              {/* 操作按钮 */}
              <div className="flex space-x-3 mt-6">
                <motion.button
                  whileHover={{ scale: 1.02 }}
                  whileTap={{ scale: 0.98 }}
                  onClick={() => setShowSaveTemplateModal(false)}
                  className={cn(
                    "flex-1 px-4 py-2 rounded-lg font-medium transition-colors",
                    isDark 
                      ? "bg-gray-700 hover:bg-gray-600 text-gray-300" 
                      : "bg-gray-200 hover:bg-gray-300 text-gray-700"
                  )}
                >
                  取消
                </motion.button>
                <motion.button
                  whileHover={{ scale: 1.02 }}
                  whileTap={{ scale: 0.98 }}
                  onClick={handleSaveAsTemplate}
                  className="flex-1 px-4 py-2 rounded-lg font-medium bg-gradient-to-r from-purple-500 to-purple-600 hover:from-purple-600 hover:to-purple-700 text-white transition-all duration-200 shadow-lg"
                >
                  <i className="fa-solid fa-save mr-2"></i>
                  保存模板
                </motion.button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
} 